package com.weilai.service.serviceImpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.controller.exceptionHandler.SystemException;
import com.weilai.dao.PostsDao;
import com.weilai.dao.UserDao;
import com.weilai.domain.Comments;
import com.weilai.domain.Likes;
import com.weilai.domain.Posts;
import com.weilai.domain.User;
import com.weilai.service.PostsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;


@Service
public class PostsServiceImpl implements PostsService {
    @Autowired
    private PostsDao postsDao;
    private UserDao userDao;
    //添加帖子
    @Override
    public void add(Posts posts) {
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDate = now.format(formatter);
        posts.setCreatedAt(formattedDate);
        this.postsDao.add(posts);
    }
    //根据id删除帖子
    @Override
    public void deleteById(int id) {
        this.postsDao.deleteById(id);
    }
    //修改帖子
    @Override
    public void update(Posts posts) {
        LocalDateTime now = LocalDateTime.now();
        Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDate = now.format(formatter);
        posts.setUpdatedAt(formattedDate);
        this.postsDao.update(posts);
    }
    //查询所有帖子
    @Override
    public PageInfo<Posts> selectAll(int pageNum, int pageSize) {
        // 开启分页
        PageHelper.startPage(pageNum, pageSize);
        List<Posts> posts = postsDao.selectAll();
        // 封装分页信息
        return new PageInfo<>(posts);
    }

    //查询别人所有文章
    @Override
    public List<Posts> selectAllArticle(int userId) {
        return this.postsDao.selectAllArticle(userId);
    }
    //查询自己所有文章
    @Override
    public List<Posts> selectMyAllArticle(int userId){
        return this.postsDao.selectMyAllArticle(userId);
    }
    //查询别人所有讨论
    @Override
    public List<Posts> selectAllDiscussion(int userId) {
        return this.postsDao.selectAllDiscussion(userId);
    }
    //查询自己所有讨论
    @Override
    public List<Posts> selectMyAllDiscussion(int userId){
        return this.postsDao.selectMyAllDiscussion(userId);
    }
    //根据标题关键字查询帖子
    @Override
    public List<Posts> selectByTitle(String title) {
        List<Posts> posts = postsDao.selectByTitle(title);
        if(posts==null||posts.isEmpty())
            return new ArrayList<>();
        else
            return posts;

    }
    //根据时间范围查询帖子
    @Override
    public List<Posts> selectByDate(String date1, String date2){
        List<Posts> posts = postsDao.selectByDate(date1, date2);
        if(posts==null||posts.isEmpty()){
            return new ArrayList<>();
        }
        else
            return posts;
    }
    //按userId查询
    @Override
    public List<Posts> selectByUserId(int id) {
        List<Posts> posts = postsDao.selectByUserId(id);
        return posts;
    }

    @Override
    public List<Posts> selectData(int userId) {
        try{
            return postsDao.selectData(userId);
        } catch (Exception e) {
            throw new BusinessException(Code.SYSTEM_DB_ERROR, "按id查询文章数据时数据库出错");
        }
    }


    //按id查询
    @Override
    public Posts selectById(int id) {
        Posts posts = postsDao.selectById(id);
        postsDao.incrementViewCount(posts.getId());
        return posts;
    }
    //进入帖子前查询用户是否点赞
    @Override
    public boolean isLikedByUser(int userId, int postId) {
        return postsDao.countUserLiked(userId, postId) > 0;
    }
    //进入首页前查询用户是否点赞
    @Override
    public int isLike(int postId, int userId) {
        int count=postsDao.countUserLiked(userId, postId);
        if(count==0){
            return 0;
        }
        return 1;
    }

//    @Override
//    public String toggleLike(int userId, int postId) {
//        int count = postsDao.countUserLiked(userId, postId);
//        if (count == 0) {
//            postsDao.incrementLikeCount(postId);
//            postsDao.insertLikeRecord(userId, postId);
//            return "点赞成功";
//        } else {
//            Likes likeRecord = postsDao.selectLikeRecord(userId, postId);
//            if (likeRecord != null) {
//                int likeId = likeRecord.getId();
//                postsDao.cancelLikeRecord(likeId);
//                postsDao.decrementLikeCount(postId);
//                return "取消点赞成功";
//            }
//        }
//        return "操作异常";
//    }
@Override
public Map<String, Object> like(int userId, int postId) {
    Map<String, Object> result = new HashMap<>();
    int count = postsDao.countUserLiked(userId, postId);
    if (count == 0) {
        postsDao.incrementLikeCount(postId);
        postsDao.insertLikeRecord(userId, postId);
        result.put("message", "点赞成功");
    }
    // 获取更新后的点赞数
    int likeCount = postsDao.getLikeCount(postId);
    result.put("likeCount", likeCount);
    return result;
}

    @Override
    public Map<String, Object> cancelLike(int userId, int postId) {
        Map<String, Object> result = new HashMap<>();
        Likes likeRecord = postsDao.selectLikeRecord(userId, postId);
        if (likeRecord != null) {
            int likeId = likeRecord.getId();
            postsDao.cancelLikeRecord(likeId,userId);
            postsDao.decrementLikeCount(postId);
            postsDao.delete(userId,postId);
            result.put("message", "取消点赞成功");
        }
        // 获取更新后的点赞数
        int likeCount = postsDao.getLikeCount(postId);
        result.put("likeCount", likeCount);
        return result;
    }

    @Override
    @Transactional
    public String comment(Comments comments,Integer userId) {
//        System.out.println("service:userId:"+userId);
//
//        User user = userDao.getById(userId);
//        System.out.println("service:user:"+user);


//        // 添加空值检查
//        if (user == null) {
//            throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "用户不存在");
//        }
//
//
//        if(!user.getStatus().equals("正常")){
//            throw new BusinessException(Code.PROJECT_ACCESS_DENIED,"您已被禁言");
//        }
        postsDao.incrementCommentCount(comments.getPostId());
        //获取当前时间
        comments.setCreatedAt(LocalDateTime.now());
        postsDao.insertCommentRecord(comments);
        return "评论成功";
    }
    @Override
    public List<Comments> getCommentsByPostId(int postId) {
        return postsDao.getCommentsByPostId(postId);
    }

    @Override
    public void view(int postId) {

        postsDao.incrementViewCount(postId);
    }

    @Override
    public void share(int postId) {

        postsDao.incrementShareCount(postId);
    }

    // 用户删除自己的评论
    @Override
    public String deleteCommentByUser(int commentId, int userId) {
        Integer postId = postsDao.getPostIdByCommentId(commentId);
        int result = postsDao.deleteCommentByUser(commentId, userId);
        if (result > 0) {
            if (postId == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND,"帖子ID为空，无法完成删除操作");
            }
            postsDao.decrementCommentCount(postId);
            return "评论删除成功";
        } else {
            return "删除失败，您可能没有权限或评论不存在";
        }
    }

    // 作者删除评论
    @Override
    public String deleteCommentByAuthor(int commentId, int userId) {
        int result = postsDao.deleteCommentByAuthor(commentId, userId);
        if (result > 0) {
           Integer postId = postsDao.getPostIdByCommentId(commentId);
            postsDao.decrementCommentCount(postId);
            return "评论删除成功";
        } else {
            return "删除失败，您可能没有权限或评论不存在";
        }
    }
    @Override
    public Comments getCommentById(int commentId) {
            // 调用DAO层获取评论
            Comments comment = postsDao.getCommentById(commentId);
        if (comment == null) {
            throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND,"评论不存在");
        }
            return comment;

    }

    //在首页根据帖子标题关键字和帖子类别关键字查询
    @Override
    public List<Posts> selectByKeywords(String keywords) {
        List<Posts> posts = postsDao.selectByKeywords(keywords);
        if(posts==null||posts.isEmpty()){
            return new ArrayList<>();
        }
        return posts;

    }
    //热搜实现
    @Override
    public List<Posts> hotPosts() {
        return postsDao.hotPosts();
    }

    //按id查询类别id
    @Override
    public int selectCategorieById(String name){
        return postsDao.selectCategorieById(name);
    }

    //按userId删除帖子
    @Override
    public void deleteByUserId(int userId){
        try {
            postsDao.deleteByUserId(userId);
        } catch (Exception e) {
            throw new BusinessException(Code.SYSTEM_DB_ERROR, "按id删除用户信息时数据库出错");
        }
    }

    @Override
    public int selectCommentCount(int id) {
        int commentsCount = postsDao.selectCommentCount(id);
        return commentsCount;
    }


}